<template>
  <view class="mine-container">
    <view class="mine-header">
      <view class="flex items-center">
        <!-- 头像 -->
        <image
          class="w-100rpx h-100rpx rounded-full"
          :src="isLogin ? userInfo.avatar : defaultAvatar"
        />
        <!-- 用户信息 -->
        <view class="ml-20rpx">
          <!-- 已登录 -->
          <view v-if="isLogin">
            <view class="text-32rpx">
              {{ userInfo.nickname }}
            </view>
            <view class="text-28rpx mt2">{{ userInfo?.username }}</view>
          </view>
          <!-- 未登录 -->
          <view v-else>
            <view class="login-tip">您还未登录，请先登录</view>
            <view class="w120rpx mt-2">
              <button class="login-btn" @click="navigateToLoginPage">登录</button>
            </view>
          </view>
        </view>
      </view>
      <!-- 编辑资料 -->
      <view v-if="isLogin" class="cursor-pointer">
        <wd-icon name="setting" @click="navigateToProfile" />
      </view>
    </view>
    <view class="home">
      <wd-card style="margin-top: 10px;">
        <template #title>
          <view style="text-align: center">
            <wd-button @click="planSelect.handleShow(stepsPlan)">
              &nbsp;&nbsp;运动目标：{{ stepsPlan }}步&nbsp;&nbsp;
              <wd-icon name="edit-outline"></wd-icon>
              &nbsp;&nbsp;
            </wd-button>
          </view>
        </template>
        <wd-loading v-if="indexLoading"></wd-loading>
        <view
          v-else
          style="
            height: 80rpx;
            padding: 10px;
            margin-top: -20px;
            display: flex;
            justify-content: space-around;
            align-items: center;
          "
        >
          <view>
            <view
              class="sportTitle"
              :style="curStep >= stepsPlan ? { color: '#82d44f' } : { color: '#fe9400' }"
            >
              {{ curStep }}步
            </view>
            <view class="sportContent">当日步数</view>
          </view>
          <view>
            <view class="sportTitle">{{ ((curStep * 0.7) / 1000).toFixed(1) }}km</view>
            <view class="sportContent">当日里程</view>
          </view>
          <view>
            <view class="sportTitle">{{ (curStep * 0.05).toFixed(1) }}Kcal</view>
            <view class="sportContent">步数消耗</view>
          </view>
        </view>
      </wd-card>
      <wd-card>
        <wd-collapse v-model="stepChart">
          <wd-collapse-item title="步数情况" name="step">
            <view class="charts-box">
              <qiun-data-charts
                :canvas2d="true"
                type="area"
                :chartData="stepOptions"
                :opts="chartOpts"
              />
            </view>
          </wd-collapse-item>
        </wd-collapse>
      </wd-card>
    </view>

    <wd-toast />
    <PlanSelect ref="planSelect" :increment="1000" :title="'每日步数'" @get-plan="getStepsPlan" />

  </view>
</template>

<script lang="js" setup>
import { useUserStore } from "@/store/modules/user";
import PlanSelect from "@/components/my-component/planSelect.vue";
import UserStepsPlanAPI from "@/api/stepsPlan/user-steps-plan";
import DecryptAPI from "@/api/system/decrypt";
import UserAPI from "@/api/system/user";
import { getToken } from "@/utils/cache";
const userStore = useUserStore();
const userInfo = computed(() => userStore.userInfo);
const isLogin = computed(() => !!userInfo.value);
const defaultAvatar = "/static/images/default-avatar.png";
const indexLoading = ref(false);
const stepChart = ref(["step"]);
const stepOptions = ref({});
const curStep = ref(0);
const stepsPlan=ref(0)
const planSelect=ref()
const chartOpts = ref({
  padding: [20, 0, 20, 0],
  xAxis: {
    fontSize: 10,
    rotateLabel: true,
    rotateAngle: 30,
  },
  yAxis: {
    disabled: true,
    max: 100,
  },
  legend: {
    show: false,
  },
  extra: {
    area: {
      type: "curve",
      opacity: 0.2,
      addLine: true,
      width: 2,
      gradient: true,
      activeType: "hollow",
    },
  },
});

onShow(async () => {
  const userInfo=await UserAPI.getProfile()
  if(userInfo.height&&userInfo.weight&&userInfo.age&&userInfo.gender){
    userStore.getInfo()
    getStepsPlan();
  }else {
    uni.navigateTo({
      url: "/pages/mine/profile/index"
    })
  }
});
onMounted(()=>{
  let token=getToken()
  if (token){
    wx.getWeRunData({
      success(res) {
        // 拿 encryptedData 到开发者后台解密开放数据
        const encryptedData = res.encryptedData;
        const iv = res.iv;
        uni
          .login({
            provider: "weixin",
          })
          .then((res) => {
            let code = res.code;
            getSessionKey(code, encryptedData, iv);
          });
      },
    });
  }
})
const getStepsPlan = () => {
  UserStepsPlanAPI.getFormData().then((res) => {
    if (res != null) {
      stepsPlan.value = res.steps;
    }
  });
};
function getSessionKey(code, encryptedData, iv) {
  let APP_ID = import.meta.env.VITE_APP_APP_ID;
  let APP_SECRET = import.meta.env.VITE_APP_APP_SECRET;
  try {
    uni.request({
      url: "https://api.weixin.qq.com/sns/jscode2session", // 请求的 URL
      method: "GET", // 请求方式，GET 或 POST
      data: {
        appid: APP_ID,
        secret: APP_SECRET,
        js_code: code,
        grant_type: "authorization_code",
      }, // 请求的参数
      success: function (res) {
        // 请求成功的回调函数
        const { session_key } = res.data;
        DecryptAPI.decrypt({ sessionKey: session_key, encryptedData, iv }).then((res) => {
          let data = res.stepInfoList;
          let xdata = [];
          let value = [];
          for (let i = data.length - 8; i < data.length; i++) {
            const item = data[i];
            let timestamp = item.timestamp;

            // 转换为毫秒（因为 JavaScript 中的 Date 对象使用的是毫秒）
            const date = new Date(timestamp * 1000); // 乘1000转换为毫秒
            const year = date.getFullYear();
            const month = String(date.getMonth() + 1).padStart(2, "0"); // 月份从0开始
            const day = String(date.getDate()).padStart(2, "0");
            // 转换为本地日期字符串
            xdata.push(`${month}-${day}`);
            value.push(item.step);
            if (i === data.length - 1) {
              curStep.value = item.step;
            }
          }
          stepOptions.value = { categories: xdata, series: [{ data: value, name: "步数" }] };
          indexLoading.value = false;
          // chartOpts.value.xAxis.data=
        });
      },
    });

    // 你可以在这里保存 openid 和 session_key，供后续使用
  } catch (error) {
    console.error("获取 session_key 错误:", error);
  }
}
// 登录
const navigateToLoginPage = () => {
  uni.navigateTo({ url: "/pages/login/index" });
};
// 个人信息
const navigateToProfile = () => {
  uni.navigateTo({ url: "/pages/mine/profile/index" });
};

// 设置
const navigateToSettings = () => {
  uni.navigateTo({ url: "/pages/mine/settings/index" });
};
</script>

<style lang="scss" scoped>
.mine-container {
  .mine-header {
    display: flex;
    align-items: start;
    justify-content: space-between;
	border-radius: 10px;
	margin: 15px;
    padding: 60rpx 20rpx;
    color: #fff;
    background: linear-gradient(60deg, #517cf0, #769ef5);

    .login-tip {
      font-size: 28rpx;
      color: #fff;
    }
    .login-btn {
      font-size: 28rpx;
      line-height: 50rpx;
      color: #4d80f0;
      border-radius: 10rpx;
    }
    .cursor-pointer {
      display: flex;
      align-items: center;
      justify-content: center;
      margin: auto;
      margin-right: 10rpx;
    }
  }
}

@keyframes spin {
  0% {
    transform: rotate(0deg);
  }
  100% {
    transform: rotate(360deg);
  }
}
</style>
